package com.buyouchina.web.action.product;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import com.buyouchina.bean.area.Province;
import com.buyouchina.bean.privilege.Role;
import com.buyouchina.bean.privilege.User;
import com.buyouchina.bean.product.OrderForm;
import com.buyouchina.bean.product.Outlets;
import com.buyouchina.bean.product.Product;
import com.buyouchina.bean.product.Record;
import com.buyouchina.bean.product.Statistical;
import com.buyouchina.bean.product.OrderForm.Type;
import com.buyouchina.bean.product.Outlets.OutletsType;
import com.buyouchina.bean.product.Statistical.StatisticalType;
import com.buyouchina.service.area.ProvinceService;
import com.buyouchina.service.privilege.UserService;
import com.buyouchina.service.product.OrderService;
import com.buyouchina.service.product.OutletsService;
import com.buyouchina.service.product.ProductService;
import com.buyouchina.service.product.RecordService;
import com.buyouchina.service.product.StatisticalService;
import com.buyouchina.utils.Pagination;
import com.buyouchina.utils.ProvinceUtil;
import com.buyouchina.utils.SiteUrl;
import com.buyouchina.utils.UserUtil;
import com.buyouchina.web.action.BaseAction;
import com.buyouchina.web.action.privilege.Permission;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@Controller("OrderAction")
public class OrderAction extends BaseAction implements ModelDriven<OrderForm>,
		Preparable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private OrderForm order = new OrderForm();

	@Resource(name = "orderServiceBean")
	private OrderService orderService;
	@Resource(name = "productServiceBean")
	private ProductService productService;
	@Resource(name = "outletsServiceBean")
	private OutletsService outletsService;
	@Resource(name = "statisticalServiceBean")
	private StatisticalService statisticalService;
	@Resource(name = "userServiceBean")
	private UserService userService;
	@Resource(name = "provinceServiceBean")
	private ProvinceService provinceService;

	private List<OrderForm> orderList = new ArrayList<OrderForm>();
	private List<Product> productList = new ArrayList<Product>();
	private List<Record> recordList = new ArrayList<Record>();
	private List<Outlets> outletsList = new ArrayList<Outlets>();
	private Integer orderid;

	@Resource(name = "recordServiceBean")
	private RecordService recordService;
	private Record record;
	private Integer[] productid;
	private Double[] quantity;
	private String[] unit;
	private Double[] price;
	private Double[] amounts;
	private Integer customerid;
	private Integer outletsid;

	// 查看订单
	public String view() {
		order = orderService.find(order.getId());
		recordList = new ArrayList<Record>(order.getRecords());
		if (order.getType() != null && order.getType().equals(Type.SELLSORDER)) {
			return "viewSellOrder";
		}
		return "view";
	}

	// 修改订单view
	public String modify() {
		order = orderService.find(order.getId());
		recordList = new ArrayList<Record>(order.getRecords());
		return "modify";
	}

	// 添加订单视图
	@Permission(model = "order", privilegeValue = "insert")
	public String add() {
		User user=(User) session.get("user");
		Outlets ot = (Outlets) session.get("outlets");
		productList = productService.list(true, ot.getId());
		if (order.getType() != null) {
			return "createSellOrder";
		}
		// 如果是进货单
		else {
			if(user.getRole().equals(Role.CLDSSM)){
				outletsList=outletsService.list("from Outlets o where o.proxyManager.id=?1",user.getId());
			}else{
//				outletsList = outletsService.getScrollData().getResultlist();
				outletsList=outletsService.list("from Outlets o where o.type=?1", OutletsType.STORE);
			}
			return "add";
		}
	}

	// 创建订单
	@Permission(model = "order", privilegeValue = "insert")
	public String create() {

		return MESSAGE;
	}

	// 保存订单
	@Permission(model = "order", privilegeValue = "insert")
	public String update() {
		Double totalAmount = 0.0;
		Product product = null;
		Outlets outlets = (Outlets) session.get("outlets");
		Outlets ot = outletsService.find(outletsid);
		for (int i = 0; i < productid.length; i++) {
			if (productid[i] != null) {
				record = new Record();
				product = productService.find(productid[i]);

				record.setQuantity(quantity[i]);
				record.setPrice(price[i]);
				if (price[i] != null) {
					record.setAmount(quantity[i] * price[i]);
					totalAmount += quantity[i] * price[i];
				}

				record.setProduct(product);
				record.setUser((User) session.get("user"));
				recordService.save(record);
				order.getRecords().add(record);

			}
		}
		order.setProvince(ot.getProvince());
		order.setOutlets(ot);
		order.setAmount(totalAmount);
		order.setFrom((Outlets) session.get("outlets"));
		order.setOperator((User) session.get("user"));
		orderService.save(order);
		request.setAttribute("message", "保存订单成功!!");
		if (outlets.getType().equals(OutletsType.WAREHOUSE)) {
			request.setAttribute("urladdress", SiteUrl
					.readUrl("order.listPurchase"));
		} else {
			request.setAttribute("urladdress", SiteUrl.readUrl("order.list"));
		}
		return MESSAGE;
	}

	// 发货
	public String checkout() {
		order = orderService.find(orderid);
		List<Record> records = new ArrayList<Record>(order.getRecords());
		for (int i = 0; i < records.size(); i++) {
			record = records.get(i);
			Product product = productService.find(record.getProduct().getId());
			product.setCurQuantity(product.getCurQuantity()
					- record.getQuantity());
			productService.update(product);
		}
		order.setFrom((Outlets) session.get("outlets"));
		order.setStatus("已发货");
		orderService.update(order);
		request.setAttribute("message", "发货成功!!");
		request.setAttribute("urladdress", SiteUrl
				.readUrl("order.listPurchase"));
		return MESSAGE;
	}

	// 确认收货
	public String simpleUpdate() {
		order = orderService.find(orderid);
		recordList = new ArrayList<Record>(order.getRecords());
		// 遍历产品进出记录
		for (Record record : recordList) {

			Product product = record.getProduct();
			Product toProduct = productService.getByCode(product.getCode(),
					order.getOutlets().getId());
			if (toProduct != null) { // 订单发货到的店铺有这个商品
				toProduct.setCurQuantity(toProduct.getCurQuantity()
						+ record.getQuantity());
				productService.update(toProduct);
			} else {
				product = new Product(product);
				product.setOutlets(order.getOutlets());
				product.setCurQuantity(record.getQuantity());
				productService.save(product);
			}
			record.setStatus("交易成功");
			recordService.update(record);
			this.save(order.getOutlets().getProvince(), record, order);
		}

		order.setStatus("交易成功");
		orderService.update(order);
		request.setAttribute("message", "确认收货成功!!");
		request.setAttribute("urladdress", SiteUrl
				.readUrl("order.listPurchase"));
		return MESSAGE;
	}

	// 修改订单
	@Permission(model = "order", privilegeValue = "update")
	public void save(Province province, Record record, OrderForm order) {

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String startTime = sdf.format(new Date()) + " 00:00:00";
			String endTime = sdf.format(new Date()) + " 23:59:59";
			Statistical st = statisticalService.check(sdf1.parse(startTime),
					sdf1.parse(endTime), record.getProduct().getId(), order
							.getOutlets().getId());
			if (st != null) {
				st.setQuantity(st.getQuantity() + record.getQuantity());
				st.setProvince(province);
				statisticalService.update(st);
			} else {
				st = new Statistical();
				st.setTo(order.getOutlets());
				st.setFrom(order.getFrom());
				if (order.getType().getName().equals("销售单")) {
					st.setType(StatisticalType.SALES);
				} else {
					st.setType(StatisticalType.PURCHASE);
				}
				st.setDate(order.getDate());
				st.setProduct(record.getProduct());
				st.setProvince(province);
				st.setQuantity(record.getQuantity());
				statisticalService.save(st);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 订单列表
	@Permission(model = "order", privilegeValue = "view")
	// 查看订单
	public String list() {
		Integer recordCount = null;

		Outlets outlets = (Outlets) session.get("outlets");
		Pagination pg = new Pagination(request, response);

		if (outlets.getId() != 1) {
			recordCount = orderService.getCountByOid(outlets);
			pg.setRecordCount(recordCount);

			orderList = orderService.list(outlets, order.getType(), pg
					.getFirstResult(), pg.getPageSize());
			request.setAttribute("pagination", pg);
			if (order.getType() != null
					&& order.getType().equals(Type.SELLSORDER)) {
				productList = productService.list(true, outlets.getId());
				return "listSellOrder";
			} else {
				return "listPurchaseOrder";
			}
		} else {
			User user = (User) session.get("user");
			String hql = "from OrderForm o where o.province.id between ?1 and ?2";
			if (UserUtil.getMaxLevel(user) == 7000||UserUtil.getMaxLevel(user)==6000) {
				List<Province> provinces = new ArrayList<Province>(user
						.getProvinces());
				Province province = provinces.get(0);
				Integer pid = province.getId();
				pg.setRecordCount(orderService.getCount(pid, ProvinceUtil
						.getLastIndexOfProvince(provinceService, pid)));
				orderList = orderService.list(hql, pg.getFirstResult(), pg
						.getPageSize(), pid, ProvinceUtil
						.getLastIndexOfProvince(provinceService, pid));

			} else {
				pg.setRecordCount(((Long) orderService.getCount()).intValue());
				orderList = orderService.getScrollData(pg.getFirstResult(),
						pg.getPageSize()).getResultlist();
			}
			request.setAttribute("pagination", pg);
			return SUCCESS;
		}

	}

	// 删除订单
	@Permission(model = "order", privilegeValue = "delete")
	public void del() {
		orderService.delete(order.getId());
	}

	// 销售单创建
	public String createSellOrder() {

		User user = (User) session.get("user");
		user = userService.find(user.getId());

		order.setOutlets((Outlets) session.get("outlets"));
		order.setType(Type.SELLSORDER);
		Double totalAmount = 0.0, totalQuantity = 0.0;
		Product product = null;

		for (int i = 0; i < productid.length; i++) {
			if (productid[i] != null) {

				product = productService.find(productid[i]);

				// 存储一条商品记录
				record = new Record(quantity[i], null, price[i], quantity[i]
						* price[i], new Date(), "销售成功", user, product);
				recordService.save(record);

				// 更新一条商品信息
				product.setCurQuantity(product.getCurQuantity() - quantity[i]);
				productService.update(product);

				order.getRecords().add(record);
				totalAmount += quantity[i] * price[i];
				totalQuantity += quantity[i];

			}
		}
		order.setTotalQuantity(totalQuantity);
		order.setOperator(user);
		order.setAmount(totalAmount);
		orderService.save(order);
		recordList = new ArrayList<Record>(order.getRecords());
		// 遍历产品进出记录
		for (Record record : recordList) {

			this.save(order.getOutlets().getProvince(), record, order);
		}
		request.setAttribute("message", "销售录入成功!!");
		request.setAttribute("urladdress", SiteUrl
				.readUrl("order.listSellOrder"));

		return MESSAGE;
	}

	public String tongji() {

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String startTime = sdf.format(new Date()) + " 00:00:00";
			String endTime = sdf.format(new Date()) + " 23:59:59";
			orderList = orderService.findByDate(sdf1.parse(startTime), sdf1
					.parse(endTime));
			return "statistical";
		} catch (Exception e) {
			e.printStackTrace();
			return SUCCESS;
		}
	}

	// 订单查询
	public String query() {
		String hql;
		/*
		 else {
			hql = "from OrderForm o where o.code=?1 and o.from.id=?2 or o.outlets.id=?3";
			orderList = orderService.list(hql, order.getCode(),
					outlets.getId(), outlets.getId());
		}
		 */
		hql = "from OrderForm o where o.code=?1";
		orderList = orderService.list(hql, order.getCode());
		return SUCCESS;
	}

	// Model Driven
	public OrderForm getModel() {
		return order;
	}

	// PREPARABLE
	public void prepare() throws Exception {
		if (orderid == null || "".equals(orderid)) {
			order = new OrderForm();
		} else {
			order = orderService.find(orderid);
		}
	}

	// getter and setter

	public List<OrderForm> getOrderList() {
		return orderList;
	}

	public void setOrderList(List<OrderForm> orderList) {
		this.orderList = orderList;
	}

	public Integer getOrderid() {
		return orderid;
	}

	public void setOrderid(Integer orderid) {
		this.orderid = orderid;
	}

	public Integer[] getProductid() {
		return productid;
	}

	public void setProductid(Integer[] productid) {
		this.productid = productid;
	}

	public List<Product> getProductList() {
		return productList;
	}

	public void setProductList(List<Product> productList) {
		this.productList = productList;
	}

	public Double[] getQuantity() {
		return quantity;
	}

	public void setQuantity(Double[] quantity) {
		this.quantity = quantity;
	}

	public String[] getUnit() {
		return unit;
	}

	public void setUnit(String[] unit) {
		this.unit = unit;
	}

	public Double[] getPrice() {
		return price;
	}

	public void setPrice(Double[] price) {
		this.price = price;
	}

	public Record getRecord() {
		return record;
	}

	public void setRecord(Record record) {
		this.record = record;
	}

	public List<Record> getRecordList() {
		return recordList;
	}

	public void setRecordList(List<Record> recordList) {
		this.recordList = recordList;
	}

	public Integer getCustomerid() {
		return customerid;
	}

	public void setCustomerid(Integer customerid) {
		this.customerid = customerid;
	}

	public Double[] getAmounts() {
		return amounts;
	}

	public void setAmounts(Double[] amounts) {
		this.amounts = amounts;
	}

	public List<Outlets> getOutletsList() {
		return outletsList;
	}

	public void setOutletsList(List<Outlets> outletsList) {
		this.outletsList = outletsList;
	}

	public OrderForm getOrder() {
		return order;
	}

	public void setOrder(OrderForm order) {
		this.order = order;
	}

	public Integer getOutletsid() {
		return outletsid;
	}

	public void setOutletsid(Integer outletsid) {
		this.outletsid = outletsid;
	}
}
